//
//  WXLSearchViewController.m
//  段子手
//
//  Created by dllo on 16/3/28.
//  Copyright © 2016年 JokesTeam. All rights reserved.
//

#import "WXLSearchViewController.h"

@interface WXLSearchViewController ()<INSSearchBarDelegate, UITableViewDataSource, UITableViewDelegate, WXLHotSongsTableViewCellDelegate>

@property (nonatomic, retain) INSSearchBar *search; /**< 搜索bar */
@property (nonatomic, retain) UIView *barView;
@property (nonatomic, retain) UIImageView *bigImage; /**< 当搜索信息为空时显示 */
@property (nonatomic, retain) UILabel *noLabel; /**< 隐藏的显示信息的label */

@property (nonatomic, retain) NSMutableArray *searchDataArr; /**< 搜索到的结果数组 */
@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) WXLSearchModel *tempModel;
@property (nonatomic, retain) UIView *hiddenView; /**< 影藏的view */
@property (nonatomic, retain) UITableView *hiddenViewTableView; /**< 隐藏的view上的tableView */

@property (nonatomic, assign) NSInteger page; /**< 数据的页数 */

@end

@implementation WXLSearchViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _page = 1;
        self.searchDataArr = [NSMutableArray new];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建图片
    [self creatImagView];
    // 创建头上的view
    [self createTitleView];
    // 创建隐藏的view
    [self createHiddenView];
    // 创建searchBar
    [self creatSeach];
    // 创建tableView
    [self createTableView];
    // 添加上拉刷新控件
    [self addFooter];
}

// 创建tableViewView （搜索结果的显示）
- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kUIScreenWidth, kUIScreenHeight - 64 - 60) style:UITableViewStylePlain];
    _tableView.hidden = YES;
    [self.view addSubview:_tableView];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.backgroundColor = [UIColor clearColor];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [_tableView registerClass:[WXLHotSongsTableViewCell class] forCellReuseIdentifier:@"WXLHotSongsTableViewCell"];

}

// 创建隐藏的view
- (void)createHiddenView {
    self.hiddenView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, kUIScreenWidth, kUIScreenHeight - 64 - 60)];
    [self.view addSubview:_hiddenView];
    _hiddenView.hidden = YES;
    _hiddenView.backgroundColor = [UIColor clearColor];
    
    self.hiddenViewTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _hiddenView.frame.size.width, _hiddenView.frame.size.height) style:(UITableViewStylePlain)];
    [self.hiddenView addSubview:_hiddenViewTableView];
    _hiddenViewTableView.backgroundColor = [UIColor clearColor];
    _hiddenViewTableView.showsVerticalScrollIndicator = NO;
    
    _hiddenViewTableView.delegate = self;
    _hiddenViewTableView.dataSource = self;
    
    [_hiddenViewTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];

}

/** 创建searchBar */
- (void)creatSeach {
    self.search = [[INSSearchBar alloc] initWithFrame:CGRectMake(5, 10, _barView.frame.size.width - 20, 30)];
    _search.delegate = self;
    _search.layer.cornerRadius = _search.frame.size.height / 2;
    _search.layer.masksToBounds = YES;
    _search.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _search.layer.borderWidth = 2;
    _search.searchField.placeholder = @"请输入你要搜索的歌曲信息";
    [_barView addSubview:_search];
}

/** 创建头上的view */
- (void)createTitleView {
    self.barView = [[UIView alloc] initWithFrame:CGRectMake(40, 20, kUIScreenWidth - 40, 44)];
    [self.view addSubview:_barView];
    _barView.backgroundColor = [UIColor clearColor];
}

- (void)creatImagView {
    self.bigImage = [[UIImageView alloc] initWithFrame:CGRectMake(kUIScreenWidth / 2 / 2, 64, kUIScreenWidth / 2, (kUIScreenHeight - 64 - 60) / 2)];
    [self.view addSubview:_bigImage];
    _bigImage.center = self.view.center;
    _bigImage.image = [UIImage imageNamed:@"searchmore"];
    
    self.noLabel = [[UILabel alloc] initWithFrame:CGRectMake(-kUIScreenWidth / 4, _bigImage.frame.size.height - 50, kUIScreenWidth, 60)];
    [self.bigImage addSubview:_noLabel];
    _noLabel.textAlignment = NSTextAlignmentCenter;
    _noLabel.text = @"请点击搜索输入你要搜索的歌曲信息";
    _noLabel.backgroundColor = [UIColor clearColor];
    _noLabel.textColor= RGBA(217, 218, 218, 1);
    _noLabel.font = [UIFont systemFontOfSize:20 weight:1];
}



#pragma mark - tableView Delegate & dataSource]
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _hiddenViewTableView) {
        NSArray *songArr = _tempModel.songArr;
        NSArray *singerArr = _tempModel.singerArr;
        NSArray *keywrodArr = _tempModel.keywordArr;
        if (section == 0) {
            return keywrodArr.count;
        } else if (section == 1) {
            return songArr.count;
        }
        return singerArr.count;
    }
    return _searchDataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _hiddenViewTableView) {
        NSArray *songArr = _tempModel.songArr;
        NSArray *singerArr = _tempModel.singerArr;
        NSArray *keywrodArr = _tempModel.keywordArr;
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
        cell.backgroundColor = [UIColor clearColor];
        
        if (indexPath.section == 0) {
            WXLSearchKeywordModel *model = keywrodArr[indexPath.row];
            cell.imageView.image = [UIImage imageNamed:@"iconfont-weibiaoti1"];
            cell.textLabel.text = model.val;
        } else if (indexPath.section == 1) {
            WXLSeachSongModel *model = songArr[indexPath.row];
            cell.imageView.image = [UIImage imageNamed:@"iconfont-yinle-3"];
            cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@", model.name, model.singer_name];
        } else {
            WXLSearchSingerModel *model = singerArr[indexPath.row];
            cell.imageView.image = [UIImage imageNamed:@"iconfont-geshou"];
            cell.textLabel.text = [NSString stringWithFormat:@"%@(%@)", model.singer_name, model.alias_name];
        }
        return cell;
    }
    WXLHotSongsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WXLHotSongsTableViewCell"];
    cell.backgroundColor = [UIColor clearColor];
    WXLSongsModel *model = _searchDataArr[indexPath.row];
    cell.model = model;
    cell.indexPath = indexPath;
    cell.delegate = self;
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == _hiddenViewTableView) {
        return 3;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _tableView) {
        
        return 60;
    }
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _hiddenViewTableView) {
        WXLHotSongsTableViewCell *cell = (WXLHotSongsTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        _page = 1;
        _tableView.hidden = NO;
        _hiddenView.hidden = YES;
        [self dataHandleFromAboutSearch:cell.textLabel.text];
    } else if (tableView == _tableView) {
        WXLSongsModel *model = _searchDataArr[indexPath.row];
        self.blockChangeImage(model.picUrl);
        [PLAYMUSIC playMusicWithAvUrl:_searchDataArr dex:indexPath.row];
        [PLAYMUSIC startPlay];
    }
}



#pragma mark - WXLHotSongsTableViewCellDelegate
- (void)mVButtonAtionClick:(WXLSongsModel *)songsModel {
    WXLPLAYVIDEO.songsModel = songsModel;
    [PLAYMUSIC pausePlay];
    
    [self presentViewController:WXLPLAYVIDEO animated:YES completion:nil];
}



#pragma mark - search bar delegate
/** 点击后返回一个frame 改变searchbar 位置  02*/
//- (CGRect)destinationFrameForSearchBar:(INSSearchBar *)searchBar {
//    return CGRectMake(0, 0, 0, 0);
//}

/** 点击后将要开始变化的时候  01*/
- (void)searchBar:(INSSearchBar *)searchBar willStartTransitioningToState:(INSSearchBarState)destinationState {

    
}

/** 搜索按钮停止时触发 03 */
- (void)searchBar:(INSSearchBar *)searchBar didEndTransitioningFromState:(INSSearchBarState)previousState {
    
    
}

/** 点击键盘的搜索进行搜索  */
- (void)searchBarDidTapReturn:(INSSearchBar *)searchBar {
    _hiddenView.hidden = YES;
    _tableView.hidden = NO;
    _page = 1;
    [self dataHandleFromAboutSearch:searchBar.searchField.text];
}

/** search 中搜索的内容变化时执行  04 05*/
- (void)searchBarTextDidChange:(INSSearchBar *)searchBar {
    _page = 1;
    _bigImage.hidden = YES;
    _hiddenView.hidden = NO;
    _tableView.hidden = YES;
    [self dataHandelFromUrl:searchBar.searchField.text];
    
}



- (void)addFooter {
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        _page++;
        [self dataHandleFromAboutSearch:_search.searchField.text];
    }];
    
    
    [footer setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载 ..." forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据" forState:MJRefreshStateNoMoreData];
    
    // 设置字体
    footer.stateLabel.font = [UIFont systemFontOfSize:17];
    
    // 设置颜色
    footer.stateLabel.textColor = [UIColor lightGrayColor];
    self.tableView.mj_footer = footer;
}



#pragma mark - 数据处理s
- (void)dataHandleFromAboutSearch:(NSString *)keyStr {
    NSString *urlStr = [NSString stringWithFormat:@"http://search.dongting.com/song/search?s=s200&cpu_model=Qualcomm MSM8974PRO-AB&client_id=543ea07407b245ee8cb285a277c41216&mid=MI+3W&size=50&utdid=VGGJcU4veJsDACPAEYL62k1V&q=%@&rom=Xiaomi%%2Fcancro%%2Fcancro%%3A6.0.1%%2FMMB29M%%2F6.3.10%%3Auser%%2Frelease-keys&cpu=msm8974&v=v8.4.0.2016022715&imei=863360026086235&ram=1893508 kB&page=%ld&imsi=460019890404407&address=辽宁省大连市沙河口区五一路314&agent=none&longitude=0.0&hid=1501420936418474&net=2&from=android&app=ttpod&os=6.0.1&alf=alf700159&splus=6.0.1%%2F23&api_version=1.0&active=0&tid=0&latitude=0.0&f=f168&resolution=1080x1920&uid=863360026086235&language=zh&user_id=0", keyStr, _page];
    [WxlAPPTools GETWithURL:urlStr par:nil success:^(id responseObject) {
        NSArray *tempArr = [WXLSongsModel modelHandelWithArray:responseObject[@"data"]];
        if (_searchDataArr.count && _page == 1) {
            [_searchDataArr removeAllObjects];
        }
        if (tempArr.count) {
            for (WXLSongsModel *model in tempArr) {
                [self.searchDataArr addObject:model];
            }
        } else if (!tempArr.count && _page == 1) {
            _bigImage.hidden = NO;
            _noLabel.text = @"你搜索的内容不存在";
            _tableView.hidden = YES;
        }
        [_tableView reloadData];
    
        [_tableView.mj_footer endRefreshing];
    } filed:^(NSError *error) {
        NSLog(@"error:%@", error);
    }];
}

- (void)dataHandelFromUrl:(NSString *)keyStr {
    NSString *urlStr = [NSString stringWithFormat:@"http://so.ard.iyyin.com/sug/sugAll?v=v8.4.0.2016022715&alf=alf700159&s=s200&hid=1501420936418474&tid=0&utdid=VGGJcU4veJsDACPAEYL62k1V&q=%@&uid=863360026086235&f=f168&net=2&app=ttpod&imsi=460019890404407", keyStr];
    [WxlAPPTools GETWithURL:urlStr par:nil success:^(id responseObject) {
        
        self.tempModel = [WXLSearchModel modelWithDic:responseObject[@"data"]];
        [_hiddenViewTableView reloadData];
    } filed:^(NSError *error) {
        NSLog(@"error:%@", error);
    }];
}



#pragma mark - button点击
- (void)leftReturnItemAction:(UIBarButtonItem *)item {
    [super leftReturnItemAction:item];
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
